package com.example.springboot.controller;

import com.example.springboot.entity.Order;
import com.example.springboot.mapper.ApprovalMapper;
import com.example.springboot.mapper.OrderMapper;
import com.example.springboot.mapper.UserMapper;
import com.example.springboot.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/orders")
public class OrderController {
    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderService orderService;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private ApprovalMapper approvalMapper;

    //用get请求查询数据库信息
    @GetMapping
    public List<Order> findAll(){
        return orderMapper.findAll();//查询所有数据
    }

    //用post请求对数据库数据进行增加和修改
    @PostMapping
    public int save(@RequestBody Order order){
        Integer purchaserId = userMapper.selectId(order.getBuyerName());
        order.setPurchaserId(purchaserId);
        order.setPurchaseDate(order.getPurchaseDate().substring(0,10)); //截取日期的年月日
        return orderService.save(order);//往数据库插入或更新数据
    }

    //按照审批状态分页查询
    @GetMapping("/page")
    public Map<String,Object> findStatus(@RequestParam Integer pageNum,
                                         @RequestParam Integer pageSize,
                                         @RequestParam String isApprove){
        pageNum = (pageNum - 1) * pageSize;
        Integer total = orderMapper.selectTotal(isApprove);
        List<Order> data = orderMapper.selectPage(pageNum,pageSize,isApprove);
        for(Order order : data){
            order.setBuyerName(userMapper.selectName(order.getPurchaserId()));
        }
        Map<String,Object> res = new HashMap<>();
        res.put("data",data);
        res.put("total",total);
        return res;
    }

    //审批后用post请求对数据库数据进行增加和修改
    @PostMapping("/{id}")
    public int updateApprove(@PathVariable Integer id){

        Integer approvalId = approvalMapper.findLatest();
        orderMapper.updateApproval(id,approvalId);
        return orderMapper.updateApprove(id);//往数据库插入或更新数据
    }

}
